<?php

namespace App\Services;

/**
 * WordPress插件资源URL服务
 * 处理Laravel应用在WordPress插件环境中的静态资源路径
 */
class WordPressAssetService
{
    /**
     * 获取插件的基础URL
     */
    public static function getPluginBaseUrl(): string
    {
        // 如果在WordPress环境中，使用WordPress函数获取插件URL
        if (function_exists('plugin_dir_url')) {
            // 获取插件根目录URL
            $pluginFile = dirname(__DIR__, 3) . '/wp-lara-press.php';
            return plugin_dir_url($pluginFile);
        }

        // 如果不在WordPress环境中，尝试从HTTP_HOST构建
        if (isset($_SERVER['HTTP_HOST'])) {
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
            $host = $_SERVER['HTTP_HOST'];

            // 假设插件在标准WordPress路径中
            return $protocol . '://' . $host . '/wp-content/plugins/wp-lara-press/';
        }

        // 默认回退
        return 'https://new.sohajob.com/wp-content/plugins/wp-lara-press/';
    }

    /**
     * 获取Laravel应用的公共目录URL
     */
    public static function getLaravelPublicUrl(): string
    {
        return self::getPluginBaseUrl() . 'api/public/';
    }

    /**
     * 获取Scribe资源的完整URL
     */
    public static function getScribeAssetUrl(string $path = ''): string
    {
        $baseUrl = self::getLaravelPublicUrl();
        return $baseUrl . 'vendor/scribe/' . ltrim($path, '/');
    }

    /**
     * 获取API前缀
     */
    public static function getApiPrefix(): string
    {
        return defined('WP_LARA_PRESS_API_PREFIX') ? WP_LARA_PRESS_API_PREFIX : 'api';
    }

    /**
     * 获取API基础URL
     */
    public static function getApiBaseUrl(): string
    {
        if (function_exists('home_url')) {
            return home_url('/' . self::getApiPrefix() . '/');
        }

        if (isset($_SERVER['HTTP_HOST'])) {
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
            $host = $_SERVER['HTTP_HOST'];
            return $protocol . '://' . $host . '/' . self::getApiPrefix() . '/';
        }

        return 'https://new.sohajob.com/' . self::getApiPrefix() . '/';
    }

    /**
     * 设置Laravel的Asset URL配置
     */
    public static function configureAssetUrl(): void
    {
        $assetUrl = self::getLaravelPublicUrl();

        // 设置Laravel的asset URL配置
        config(['app.asset_url' => rtrim($assetUrl, '/')]);

        // 设置APP_URL为API基础URL
        config(['app.url' => rtrim(self::getApiBaseUrl(), '/')]);
    }
}
